<template>
  <avue-select
    v-model="text"
    :dic="dic"
    :props="props"
    :placeholder="placeholder"
    :disabled="disabled"
  >
  </avue-select>
</template>

<script>
export default {
  name: "TicketNameSelect",
  inject: {
    formSafe: { default: null }
  },
  data() {
    return {
      text: undefined
    };
  },
  props: {
    value: String,
    ticketAmountKey: String,
    ticketCountKey: String,
    valueKey: String,
    unitKey: String,
    row: Object,
    dic: {
      type: Array,
      default: () => []
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: "subName",
          value: "subEnName"
        };
      }
    },
    placeholder: String,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    value: {
      handler(val) {
        this.text = val;
      },
      immediate: true
    },
    text: {
      handler(val) {
        this.$emit("input", val);
        this.handleTicketNameChange(val);
      },
      immediate: true
    }
  },
  methods: {
    handleTicketNameChange(value) {
      if (!value) {
        this.setFormValue(this.ticketAmountKey, undefined);
        this.setFormValue(this.ticketCountKey, undefined);
        this.setFormValue(this.valueKey, undefined);
        this.setFormValue(this.unitKey, undefined);
        return;
      }
      for (let d of this.dic) {
        if (d.subEnName == value) {
          this.setFormValue(this.ticketAmountKey, d.ticketAmount);
          this.setFormValue(this.ticketCountKey, d.ticketCount);
          let value = d.ticketAmount != null ? d.ticketAmount : d.ticketCount;
          let unit = d.ticketAmount != null ? "元" : "次";
          this.setFormValue(this.valueKey, value);
          this.setFormValue(this.unitKey, unit);
          break;
        }
      }
    },
    setFormValue(key, value) {
      if (key) {
        value = value == null ? undefined : value;
        if (this.row) {
          this.$set(this.row, key, value);
        } else if (this.formSafe) {
          this.formSafe.value[key] = value;
        }
      }
    }
  }
};
</script>

<style></style>
